import 'dart:async';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';

import 'hero_image_swiper_plugin.dart';
import 'slide_hero_image_page.dart';

/// 多图片小部件查看, 自己封装的
///
/// 左右不能滑动出视图外
class HeroSwiperSlideImagePage extends StatefulWidget {
  HeroSwiperSlideImagePage({
    required this.index,
    required this.imageUrls,
    Key? key,
  }) : super(key: key);
  final int index;
  final List<String> imageUrls;

  @override
  _HeroSwiperSlideImagePageState createState() =>
      _HeroSwiperSlideImagePageState();
}

class _HeroSwiperSlideImagePageState extends State<HeroSwiperSlideImagePage> {
  final StreamController<int> rebuildIndex = StreamController<int>.broadcast();

  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: <Widget>[
        ExtendedImageGesturePageView.builder(
          controller: ExtendedPageController(
            initialPage: widget.index,
          ),
          itemBuilder: (BuildContext context, int index) {
            String imageUrl = widget.imageUrls[index];
            return SlideHeroImagePage(
              imageUrl: imageUrl,
              // 拼接上index是为了避免同一个页面,图片路径相同时页面奔溃
              heroTag: "$imageUrl-$index",
            );
          },
          itemCount: widget.imageUrls.length,
          onPageChanged: (int index) {
            _currentIndex = index;
            rebuildIndex.add(index);
          },
          scrollDirection: Axis.horizontal,
          physics: const ClampingScrollPhysics(),
        ),
        Positioned(
          bottom: 0.0,
          left: 0.0,
          right: 0.0,
          child: HeroImageSwiperPlugin(
            widget.imageUrls,
            _currentIndex,
            rebuildIndex,
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    rebuildIndex.close();
    super.dispose();
  }
}
